package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"homework12/cache"
	"homework12/model"
	"strconv"
	"time"
)

func Add(c *gin.Context) {

	name := c.PostForm("name")
	content := c.PostForm("content")
	price, _ := strconv.Atoi(c.PostForm("price"))

	if name == "" || content == "" || price == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}

	data := model.Orders{
		Name:    name,
		Content: content,
		Price:   price,
	}
	model.DB.Create(&data).Debug()

	redis_key := "orders_add" + strconv.Itoa(int(data.ID))
	var orders model.Orders
	model.DB.Where("id=?", data.ID).First(&orders).Debug()
	jsonData, _ := json.Marshal(orders)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func Del(c *gin.Context) {
	id := c.PostForm("id")

	var orders model.Orders
	err := model.DB.Where("id=?", id).Delete(&orders).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}

	redis_key := "order_del_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

//func List(c *gin.Context) {
//	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
//	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
//	offset := (page - 1) * size
//
//	var orders []model.Orders
//
//	redis_key := "order_list"
//	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
//
//	if redisData == "" {
//		model.DB.Offset(offset).Limit(size).Find(&orders).Debug()
//		jsonData, _ := json.Marshal(&orders)
//		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
//	} else {
//		json.Unmarshal([]byte(redisData), &orders)
//	}
//
//	var total int64
//	model.DB.Model(&model.Orders{}).Count(&total).Debug()
//
//	c.JSON(200, gin.H{
//		"code":  500,
//		"msg":   "获取列表成功",
//		"data":  orders,
//		"total": total,
//	})
//	return
//}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))
	offset := (page - 1) * size

	var orders []model.Orders

	redis_key := "orders_list_"
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		model.DB.Offset(offset).Limit(size).Find(&orders)
		jsonData, _ := json.Marshal(orders)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &orders)
	}

	var total int64
	model.DB.Model(&model.Orders{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "获取列表成功",
		"data":  orders,
		"total": total,
	})
}
